import React, { useEffect, useState } from 'react';
import { Form, Modal, Checkbox, Table, Card, message, Button, Icon } from 'antd';
import Pagination from '@/components/Pagination';
import moment from 'moment';
import LimitedTextArea from '../../../components/LimitedTextArea';
import { TaskOperateType } from '../../../utils';
import { auditTask } from '../../../services/index';
import { useSubTaskList } from '../../../hooks';
import { FORM_DEFAULT_LAYOUT, MODAL_DEFAULT_PARAM, MODAL_FORCE_PARAM } from '../config';
import FileFormItem from './components/FileFormItem';
import styles from './AuditRefuseActionModal.less';

const SubTaskTable = ({ tableLoading, tableData, tableTotal, query, onQueryChange }) => {
    console.log('SubTaskTable -> query', query);
    const [expand, setExpand] = useState(false);
    const getY = () => (expand ? 270 : 54);
    const handleExpand = () => {
        setExpand(!expand);
    };

    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            width: 50,
            render: (foo, bar, index) => index + 1
        },
        {
            title: '任务编号',
            dataIndex: 'taskNo',
            width: 100
        },
        {
            title: '任务名称',
            dataIndex: 'taskName',
            render: text => (
                <div
                    style={{
                        width: '100%',
                        minWidth: 100,
                        position: 'relative'
                    }}
                >
                    <span
                        style={{
                            position: 'absolute',
                            left: 0,
                            right: 0,
                            top: 0,
                            transform: 'translateY(-50%)',
                            overflow: 'hidden',
                            whiteSpace: 'nowrap',
                            textOverflow: 'ellipsis'
                        }}
                        title={text}
                    >
                        {text}
                    </span>
                </div>
            )
        },
        {
            title: '执行人',
            dataIndex: 'executor',
            width: 100
        },
        {
            title: '部门',
            dataIndex: 'executorDepartmentName',
            width: 120
        },
        {
            title: '开始时间',
            dataIndex: 'planStartTime',
            width: 120,
            render: text => (text ? moment(text).format('MM-DD HH:mm') : '')
        }
    ];
    const handlePaginationChange = p => {
        const { current, ...rest } = p;
        onQueryChange({
            ...query,
            ...rest,
            pageNo: current
        });
    };
    return (
        <Card bordered={false} className={styles.delayedForm}>
            <div style={{ paddingBottom: 10 }}>子任务清单</div>
            <Table
                rowKey="id"
                bordered={false}
                columns={columns}
                loading={tableLoading}
                dataSource={tableData}
                pagination={false}
                scroll={{ y: getY() }}
            />
            {expand && (
                <Pagination
                    total={tableTotal}
                    current={query.pageNo}
                    pageSize={query.pageSize}
                    onChange={handlePaginationChange}
                    loading={tableLoading}
                />
            )}
            <div className={styles.moreButton}>
                <Button type="link" onClick={handleExpand}>
                    {expand ? '收起' : '查看更多'}
                    {expand ? <Icon type="up" /> : <Icon type="down" />}
                </Button>
            </div>
        </Card>
    );
};
const AuditRefuseActionModal = ({ form, taskRecord, visible, setVisible, onOk }) => {
    console.log('AuditRefuseActionModal -> taskRecord', taskRecord);
    const { id, taskOperateType } = taskRecord;
    const [query, setQuery] = React.useState({ taskId: id, pageNo: 1, pageSize: 10 });
    const [tableLoading, tableData, tableTotal] = useSubTaskList(query);
    const isStartType = taskOperateType === TaskOperateType.START;
    const [subShow, setSubShow] = React.useState(!!isStartType);
    useEffect(() => {
        if (!visible) {
            return;
        }
        setSubShow(!!(isStartType && tableTotal));
    }, [tableTotal]);

    const { getFieldDecorator, validateFields } = form;
    const [confirmLoading, setConfirmLoading] = useState(false);
    const handleOk = () => {
        validateFields((err, values) => {
            console.log('AuditRefuseActionModal -> values', values);
            if (err) {
                return;
            }
            const { batchAuditSubTask, auditReason, resourceRelation } = values;
            const files = resourceRelation && [resourceRelation.uploadResourceFile];
            setConfirmLoading(true);
            auditTask(id, taskOperateType, 2, batchAuditSubTask ? 1 : 0, auditReason, files)
                .then(res => {
                    const { code, msg } = res;
                    if (code !== 10000) {
                        message.error(msg || '操作失败~~~');
                        return;
                    }
                    if (onOk) {
                        onOk();
                    }
                    setVisible(false);
                })
                .finally(() => {
                    setConfirmLoading(false);
                });
        });
    };

    return (
        <Modal
            {...MODAL_DEFAULT_PARAM}
            title="不通过"
            visible={visible}
            width={720}
            confirmLoading={confirmLoading}
            onOk={handleOk}
            destroyOnClose
            onCancel={() => setVisible(false)}
            {...MODAL_FORCE_PARAM}
        >
            <Form {...FORM_DEFAULT_LAYOUT} labelCol={{ span: 6 }}>
                <Form.Item label="审核结果">不通过</Form.Item>
                {subShow && (
                    <Form.Item label="批量处理">
                        {getFieldDecorator('batchAuditSubTask')(
                            <Checkbox>对当前任务下的子任务批量审核不通过</Checkbox>
                        )}
                    </Form.Item>
                )}
                <Form.Item label="原因">
                    {getFieldDecorator('auditReason', {
                        rules: [
                            {
                                required: true,
                                message: '请输入原因'
                            }
                        ]
                    })(<LimitedTextArea placeholder="请输入原因" maxLength={500} rows={6} />)}
                </Form.Item>
                <FileFormItem fieldName="resourceRelation" form={form}></FileFormItem>
            </Form>
            {subShow && (
                <SubTaskTable
                    query={query}
                    tableData={tableData}
                    tableTotal={tableTotal}
                    tableLoading={tableLoading}
                    onQueryChange={setQuery}
                />
            )}
        </Modal>
    );
};

export default Form.create()(AuditRefuseActionModal);
